package com.sora.basic.interceptor;

import com.sora.basic.jwt.JwtUtils;
import com.sora.basic.jwt.LoginData;
import com.sora.basic.jwt.Payload;
import com.sora.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头拿到token
        String token = request.getHeader("token");
        //等于null表示没有登录过，直接访问受限资源，查询redis数据库会报 non null key required 的异常
        if(token != null){
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //只要token过期或者没有登录，就会解密失败，抛出异常
                JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                return true;
            } catch (ExpiredJwtException e) {
                //解密失败捕获异常就返回给后置拦截器json格式的信息
                response.setContentType("application/json;chaSet=utf-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

        }

        //走到这表示没有登录过
        //向前端返回json格式的数据，在前端进行页面的跳转
        response.setContentType("application/json;chaSet=utf-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");

        //禁止走controller
        return false;
    }
}
